package com.example.demo.controller;

import com.example.demo.entity.Stu;
import com.example.demo.repository.StuRepository;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;

import java.util.List;

//@Controller
//@RequestMapping("/stu")//action访问地址的前缀
//public class StuController {
//    @Autowired
//    StuRepository repository;
//    @Autowired
//    private StuRepository stuRepository;
//
//    @ResponseBody//把返回值转换成json，这样就不用写网页了
//    @RequestMapping("/all")
//    public List<Stu> all() {
//        return repository.findAll();
//    }
//
//    @ResponseBody
//    @RequestMapping("/{id}")
//    public Stu findById(@PathVariable long id) {
//        return repository.findById(id).orElse(null);
//    }
//
//    //29 分页
//    @RequestMapping("/page")
//    public String page(@PageableDefault(size=2) Pageable pageable,Model model) {
//        Page<Stu> stus=stuRepository.findAll(pageable);
//        model.addAttribute("stus",stus);
//        return "stu_page";
//    }
//
//}

@Controller
public class StuController {
    @Autowired
    StuRepository stuRepository;

    @RequestMapping("/all_stus")
    public String allStus(Model model) {
        List<Stu> stus = stuRepository.findAll();
        model.addAttribute("stus", stus);
        return "all_stus";
    }

    @RequestMapping("/add_stu_input")
    public String add_stu_input(){
        return "add_stu";
    }

    @RequestMapping("/add_stu")
    public String add_stu(String name, double java) {
        try {
            Stu stu = new Stu(name, java);
            stuRepository.save(stu);
            return "redirect:/all_stus";
        } catch (Exception e) {
            return "redirect:/add_stu_fail";
        }
    }

    @RequestMapping("/delete_stu/{id}")
    public String delete_stu(@PathVariable Long id) {
        stuRepository.deleteById(id);
        return "redirect:/all_stus";
    }

    //29 分页
    @RequestMapping("/page")
    public String page(@PageableDefault(size=2) Pageable pageable,Model model) {
        Page<Stu> stus=stuRepository.findAll(pageable);
        model.addAttribute("stus",stus);
        return "stu_page";
    }
}